package com.example.demo.config;

import com.example.demo.service.serviceimpl.TokenServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

//urlPatterns:对哪些url进行过滤，“/*表示对所有url进行过滤”
//filterName:过滤器名称
@WebFilter(urlPatterns = {"/v2/car/*","/v2/carView/*"},filterName = "WebXFilter")
public class WebXFilter extends HttpFilter {
    @Resource
    TokenServiceImpl tokenService;
    public void init(FilterConfig config) throws ServletException { //生命周期（创建的时候）
        System.out.println("过滤器创建的时候");
    }

    public void destroy() {//生命周期（销毁的时候）
        System.out.println("过滤器销毁的时候");
    }

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream servletOutputStream = response.getOutputStream();//获取response输出对象
        try{
            if(request.getMethod().equals("OPTIONS")){
                chain.doFilter(request,response);
            }else{
                if(request.getRequestURI().equals("/v2/user/dologin")){//登录接口允许通行
                    chain.doFilter(request,response);
                }else {
                    String uaccount = request.getHeader("uaccount");
                    String token = request.getHeader("token");
                    if(tokenService.isToken(uaccount,token)){//条件符合允许通行
                        chain.doFilter(request,response);
                    }else{
                        servletOutputStream.write("{\"code\":-10001,\"msg\":\"Token不存在！\"}".getBytes());
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            servletOutputStream.write("{\"code\":-11111,\"msg\":\"Token不存在！\"}".getBytes());
        }

    }
}
